import {EnvConfig} from "@/utils/index";

export default class SSEUtils {

    private openUrl: string = '/sse/open/connect';

    private closeUrl: string = '/sse/close/connect';

    private baseUrl: string = EnvConfig.baseApi;

    private clientId: string = '';

    private clientType: string = '';

    private  chatConnection: any = null

    private isConnected: boolean = false

    private successFun = null

    private timeout = null

    constructor(baseUrl,clientId, clientType, openUrl, closeUrl, successCallback) {
        this.clientId = clientId
        this.clientType = clientType
        if (baseUrl) {
            this.baseUrl = baseUrl
        }
        if (openUrl) {
            this.openUrl = openUrl
        }
        if (closeUrl) {
            this.closeUrl = closeUrl
        }
        if (successCallback) {
            this.successFun = successCallback
        }
    }

    public openConnection() {
        const that = this
        this.chatConnection = new EventSource( this.baseUrl+ this.openUrl + `?clientId=${this.clientId}&clientType=${this.clientType}`)
        this.chatConnection.onopen = function (event) {
            that.isConnected = true
        }
        this.chatConnection.onmessage = function (event) {
            const data = event.data ? JSON.parse(event.data) : null
            if (that.successFun) {
                that.successFun(data)
            }
        }
        this.chatConnection.onerror = function (event) {
            console.log('SSE error:::', event)
            if (that.timeout) {
                clearTimeout(that.timeout)
                that.timeout = null
            }
            that.closeConnection()
            that.timeout = setTimeout(() => {
                that.openConnection()
            }, 30000)
        }
    }

    public closeConnection() {
        if (this.chatConnection) {
            this.chatConnection.close()
            this.chatConnection = null
        }
        if (this.isConnected) {
            const httpRequest = new XMLHttpRequest()
            httpRequest.open('POST', this.baseUrl + this.closeUrl + `?client_type=${this.clientType}`)
            httpRequest.send()
        }
        this.isConnected = false
    }

}